/* eslint-disable no-undef */
import { messages } from "share/common";
import React from "react";
import { connect } from "react-redux";
import { Modal, Button, Input, message, Form, Spin } from "antd";
import menuRoute from "routes/menuRoute";
import mainService from "containers/main.service";

/**
 * 扫描仪组件，用来控制富士通iX500型号扫描仪
 * 本来想写个renderProps注入扫描方法
 * 后面看只有按钮就算了
 */
class ScanSnap extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      saveFolder: "C:\\HLY-Invoice",
      isScan: false,
    };
    this.firstScan = true;
    this.firstScanSuccess = false;
    this.chat = null;
    this.hasFile = false;
    this.initialed = false;
    this.openScannerInitialed = false;
    this.unmount = false;
    this.errorCode = 0;
  }

  initial = () => {
    $.connection.hub.url = "http://localhost:8089/signalr";
    this.chat = $.connection.ssHub;
    fujitsu.scansnap.Initialize(this.chat);
    fujitsu.scansnap.bwBrightness = "0";
    fujitsu.scansnap.format = "2";
    fujitsu.scansnap.paperSize = "0";
    fujitsu.scansnap.scanningSide = "1";
    fujitsu.scansnap.colorMode = "1";
    fujitsu.scansnap.scanMode = "1";
    fujitsu.scansnap.rotation = "1";
    fujitsu.scansnap.scanType = "6";
    fujitsu.scansnap.cutType = "1";
    fujitsu.scansnap.compression = "1";
    fujitsu.scansnap.RegisterEvent("OnScannerReady", () => {});
    fujitsu.scansnap.RegisterEvent("OnScanToFile", this.onScanToFile);
    fujitsu.scansnap.RegisterEvent("OnScanToFileEnd", (ret) => {
      if (this.unmount) return;
      if (!this.hasFile) message.error(messages("common-1.key105") /*找不到文件夹，请检查路径*/);
      this.hasFile = false;
    });
    $.connection.hub.error((error) => {
      console.info("走没走到报错这一步")
      this.setState({ isScan: false });
    });
    $.connection.hub.logging = true;
    $.connection.hub.start().done(() => {});
    this.initialed = true;
  };

  onScanToFile = (readcount, name, isJsonSend, jsonResult, cid) => {
    if (this.unmount) return;
    this.hasFile = true;
    if (isJsonSend) {
      // let result = JSON.parse(jsonResult);
    }
    if (!this.firstScanSuccess) {
      localStorage.setItem("hly.scan.folder", this.state.saveFolder);
      this.firstScanSuccess = true;
    }
    fujitsu.scansnap.ConvertToBase64(readcount, (ret, data) => {
      this.setState({ isScan: false });
      if (ret > 0) {
        this.props.onScan({
          imageData: data,
        });
      }
    });
  };

  componentDidMount() {
    if (window.fujitsu) {
      this.initial();
    }
    let saveFolder = localStorage.getItem("hly.scan.folder");
    if (saveFolder) {
      this.setState({ saveFolder });
      this.firstScanSuccess = true;
    }
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.enableScan === "SCAN_SNAP" && this.props.enableScan !== "SCAN_SNAP" && !this.chat) {
      this.initial();
    }
  }

  componentWillUnmount() {
    this.unmount = true;
    this.unlinkScanSnap();
  }
  unlinkScanSnap = (reset = false) => {
    console.info('是不是走到了unlinkScanSnap这一步', this.initialed)
    if (this.initialed) {
      fujitsu.scansnap.RegisterEvent("OnScannerReady", () => {});
      fujitsu.scansnap.RegisterEvent("OnScanToFile", () => {});
      fujitsu.scansnap.RegisterEvent("OnScanToFileEnd", () => {});
      if (this.openScannerInitialed || this.errorCode === 3) {
        fujitsu.scansnap.CloseScanner().done((code) => {
          if (code !== 0 && code === 3) {
            console.info("closescanner ret = " + code);
          }
          fujitsu.scansnap.Destroy();
          $.connection.hub.stop();
          this.firstScan = true;
          this.errorCode = "";
          this.openScannerInitialed = false;
          reset && this.initial();
        });
      }
    }
  };
  handleScannerError = (code) => {
    this.errorCode = code;
    this.setState({ isScan: false });
    let errorInfo;
    console.info('handleScannerError报错信息', code)
    switch (code) {
      case 1:
        errorInfo = `${code}-请先关闭管理界面（ScanSnap Manager）再进行扫描`;
        message.error(messages("common-1.key106") /*请先关闭管理界面（ScanSnap Manager）再进行扫描*/);
        break;
      case 2:
        errorInfo = `${code}-请重新安装扫描SDK`;
        message.error(messages("common-1.key1246") /*请重新安装富士通PfuSsService*/);
        break;
      case 3:
        errorInfo = `${code}-扫描仪已被其他设备占用`;
        message.error(messages("common-1.key1247") /*扫描仪已被其他设备占用，请稍后再试或关闭其他设备*/);
        this.unlinkScanSnap(true);
        break;
      case 4:
        let currentScanServer = "PfuSsService";
        const labels = [
          messages("common-1.key1241", {
            arg1: currentScanServer,
          }) /*1. 请在任务管理器- 进程中重启名为{arg1}的驱动*/,
          messages("common-1.key1242") /*2. 重启驱动后请刷新浏览器*/,
          messages("common-1.key1243") /*3. 如仍有问题，请联系扫描设备的技术支持：4008205226 或 186 1675 9967*/,
        ];
        Modal.info({
          title: messages("common-1.key1240") /*请确保已完成以下操作*/,
          content: (
            <section>
              {labels.map((item) => (
                <p>{item}</p>
              ))}
            </section>
          ),
        });
        errorInfo = `${code}-系统异常,请联系开发人员`;
        break;
      case 5:
        message.error(messages("common-1.key109") /*错误的调用参数，请联系开发人员*/);
        errorInfo = `${code}-错误的调用参数，请联系开发人员`;
        break;
      case 6:
        errorInfo = `${code}-未连接到扫描仪或附件文件夹`;
        message.error(messages("common-1.key110") /*未连接到扫描仪或附件文件夹*/);
        break;
    }
    this.props.onEventTrack({ errorInfo });
  };
  setScanTimer = () => {
    console.info("是不是走到了setScanTimer之一步")
    if (this.setScanTimer.hasTimer) {
      clearTimeout(this.setScanTimer.hasTimer);
    }
    this.setScanTimer.hasTimer = setTimeout(() => {
      if (this.state.isScan) {
        this.setState({ isScan: false });
      }
    }, 8000);
  };
  scan = () => {
    const { saveFolder, isScan } = this.state;
    console.info("scan-isScan", isScan)
    if (isScan) {
      return !1;
    }
    if (!saveFolder) {
      message.error(messages("common-1.key111") /*请输入路径*/);
      return;
    }
    this.props.onStartScan();
    this.setState({ modalVisible: false, isScan: true });
    this.setScanTimer();
    fujitsu.scansnap.saveFolder = saveFolder;
    console.info("scan-firstScan", this.firstScan)
    if (this.firstScan) {
      fujitsu.scansnap.OpenScanner().done((code) => {
        if (code !== 0) {
          this.handleScannerError(code);
          return;
        }
        this.firstScan = false;
        this.openScannerInitialed = true;
        fujitsu.scansnap.StartScan().done((code) => {
          if (code !== 0) {
            this.handleScannerError(code);
          }
        });
      });
    } else {
      fujitsu.scansnap.StartScan().done((code) => {
        if (code !== 0) {
          this.handleScannerError(code);
        }
      });
    }
  };
  openInvoiceInfoAuthority() {
    window.open(`${window.ISIE9 ? "#" : ""}${menuRoute.getRouteItem("invoice-source-check").url}`, "_blank");
  }
  getOpenInvoiceInfoAuthority = () => {
    return mainService.checkMenuAuth(menuRoute.getRouteItem("invoice-source-check", "key"));
  };
  getShowExpenseExtra(str, linkBtn, specialStr) {
    let showExtra = str.split(specialStr);
    return (
      <div>
        {showExtra[0]}
        {linkBtn}
        {showExtra[1]}
      </div>
    );
  }
  showModal = () => {
    if (!this.props.showOCRFlag) {
      let replaceInfo = messages("common-1.key1236"); /*发票来源与查验*/
      let linkBtn = <a onClick={() => this.openInvoiceInfoAuthority()}>{replaceInfo}</a>;
      let infoMessage = messages("common-1.key1237", {
        arg1: replaceInfo,
      }); /*请管理员在{arg1}菜单，开通发票识别服务*/
      let openInvoiceAuthority = this.getOpenInvoiceInfoAuthority();
      Modal.info({
        title: messages("common-1.key71") /*说明*/,
        content: openInvoiceAuthority ? this.getShowExpenseExtra(infoMessage, linkBtn, replaceInfo) : infoMessage,
      });
      this.props.onEventTrack({ notOCRFlag: true });
      return !1;
    }
    if (this.props.enableScan !== "SCAN_SNAP") {
      const labels = [
        messages(
          "common-1.key1238"
        ) /*1. 扫描仪已和电脑保持连接，并且扫描仪处于开机状态（扫描仪型号要求：佳能DR-M1060、佳能DR-M140、富士通IX1500L、富士通IX500）*/,
        messages(
          "common-1.key1239"
        ) /*2. 驱动安装完毕，并且在任务管理器- 进程中为启动状态。各型号对应进程名称：佳能 ScanServer 、富士通 PfuSsService*/,
      ];
      Modal.info({
        title: messages("common-1.key1240") /*请确保已完成以下操作*/,
        content: (
          <section>
            {labels.map((item) => (
              <p>{item}</p>
            ))}
          </section>
        ),
      });
      this.props.onEventTrack({ disabled: true });
      return !1;
    }
    if (this.state.isScan) {
      return !1;
    }
    if (!this.firstScanSuccess) this.setState({ modalVisible: true });
    else {
      console.info("是不是走到了this.scan 这一步")
      this.scan();
    }
  };

  closeModal = () => {
    this.setState({ modalVisible: false });
  };

  render() {
    const { children, buttonProps, enableScan } = this.props;
    const { modalVisible, saveFolder, isScan } = this.state;
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 14, offset: 1 },
    };
    let wrapButtonProps = { ...buttonProps };
    wrapButtonProps.loading = !!buttonProps.loading || isScan;
    if (enableScan !== "SCAN_SNAP") {
      wrapButtonProps.type = "default";
    }
    return (
      <Button onClick={this.showModal} {...wrapButtonProps}>
        {children}
        <Modal
          visible={modalVisible}
          onOk={this.scan}
          onCancel={this.closeModal}
          okText={messages("common-1.key31") /*扫描*/}
        >
          <Form.Item
            label={messages("common-1.key112") /*附件保存到*/}
            required
            style={{ marginTop: 30, marginBottom: 0 }}
            {...formItemLayout}
            extra={messages("common-1.key113") /*找不到文件夹时，系统将自动新建文件夹*/}
          >
            <Input value={saveFolder} onChange={(e) => this.setState({ saveFolder: e.target.value })} />
          </Form.Item>
        </Modal>
      </Button>
    );
  }
}

ScanSnap.propTypes = {
  onScan: React.PropTypes.func,
  onStartScan: React.PropTypes.func,
  onEventTrack: React.PropTypes.func,
};

function mapStateToProps(state) {
  return {
    enableScan: state.main.enableScan,
  };
}

export default connect(mapStateToProps)(ScanSnap);
